#include "udpserver.hpp"
#include <iostream>
#include <memory>
#include <vector>
#include <string>

void Usage(std::string proc){
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n"
              << std::endl;
}


// 简单的发送信息
std::string Handler(const std::string &str){
    std::string ret = "Server get a message# ";
    ret += str;
    std::cout << ret << std::endl;
    return ret;
}


// 应用场景：执行客户端发送的指令
bool SafeCheck(const std::string &cmd){
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"};
    for(auto word : key_word){
        auto it = cmd.find(word);
        if(it!=std::string::npos){
            return false;
        }
    }

    return true;
}
std::string ExcuteCommand(const std::string &cmd){
    std::cout << "server get a command: " << cmd << std::endl;

    // 判断输入的指令的是否危险
    if (!SafeCheck(cmd)){
        return "Bad Command";
    }

    // 创建一个管道并执行输入的指令
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr){
        return "Command execute failed!";
    }

    // 从管道中读取内容，直到读取到空
    std::string ret;
    char buffer[4096];
    while(true){
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr){
            break;
        }
        ret += buffer;
    }

    pclose(fp);
    return ret;
}



int main(int argc, char *argv[]){
    if (argc != 2){
        Usage(argv[0]);
        exit(0);
    }
    // 使用命令行参数动态调整端口号
    uint16_t port = std::stoi(argv[1]);
    
    std::unique_ptr<UDPServer> svr(new UDPServer(port));
    svr->Init();
    //svr->Run1(Handler);
    //svr->Run1(ExcuteCommand);
    svr->Run2();

    return 0;
}